package com.kantboot.global.event;

import com.kantboot.global.event.emit.EmitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 全局事件发射器
 */
@Slf4j
@Component
public class GlobalEvent implements ApplicationContextAware {


    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 发送事件
     */
    public void emit(String code, Object ...value) {
        log.info("GlobalEventEmit.emit: code={}, value={}", code, value);
        // 获取监听事件所在的方法
        List<Method> method = EmitUtil.getMethod(code);
        if (method == null) {
            log.info("GlobalEventEmit.emit: method is null");
            return;
        }
        for (Method m : method) {
            // 获取监听事件所在的类
            Class<?> clazz = m.getDeclaringClass();
            // 获取监听事件所在的类的实例
            Object bean = applicationContext.getBean(clazz);
            // 执行监听事件
            try {
                m.invoke(bean, value);
            } catch (Exception e) {
                log.error("GlobalEventEmit.emit: error", e);
            }
        }

    }
}
